#!/usr/local/bin/python

import sys, re

filename = sys.argv[1]

locus_tag = filename.split('.')

name = locus_tag[0] + "." + locus_tag[1] + "."+ locus_tag[2]

f = open(filename, "r")

def fmt(f):
    st = '{0:.6}'.format(f)
    return st

lines = f.readlines()

m1 = re.compile('(.*)\[(.*)\] ref.*\[.*\]')

m2 = re.compile('(.*)\[(.*)\]')

m3 = re.compile('(.*)\[(.*)')

lengths = []
names = []
organisms = []

if len(lines) == 0:
    #print sys.argv[1], "\t", "-"
    pass
else:
    for l in lines:
        line = l.split('\t')
        evalue = line[1]
        percent_id = line[3]
        percent_sim = line[4]
        qstart = float(line[7])
        qstop = float(line[8])
        acc = line[9]
        hlength = line[10]
        hstart = float(line[11])
        hstop = float(line[12])
        hdef = line[13].rstrip()
        if m1.match(hdef):
            pattern = m1.match(hdef)
            definition = pattern.group(1)
            organism = pattern.group(2)
        elif m2.match(hdef):
            pattern = m2.match(hdef)
            definition = pattern.group(1)
            organism = pattern.group(2)
        elif m3.match(hdef):
            pattern = m3.match(hdef)
            definition = pattern.group(1)
            organism = pattern.group(2)
        else:
            definition = "No match"
            organism = "Couldn't identify organism"

        m = re.split('\|', acc)
#       print name, "\t", evalue, "\t", percent_id, "\t", percent_sim, "\t", \
#           m[1], "\t", qstart, "\t", qstop, "\t", hlength, "\t", hstart, "\t", \
#           hstop, "\t", definition, "\t", organism
        match_length = ((qstop - qstart + 1) / (hstop - hstart + 1)) * 100
        lengths.append(match_length)
        names.append(definition)
        organisms.append(organism)

mls = len(lengths)

if mls > 0:
    sum = 0
    for i in lengths:
        sum += i
    #print locus_tag[0] + "\t" + fmt(str(sum / mls))
    #voting process
    unique_names = set(names)
    unique_lists = list(unique_names)
    descriptions = []
    name_votes = []
    for desc in unique_lists:
        descriptions.append(desc)
        name_votes.append(names.count(desc))
    largest = max(name_votes)
    max_index = name_votes.index(largest)
    print locus_tag[0] + "\t" + "Largest vote = " + str(largest) + "\t" + descriptions[max_index]
else:
    print locus_tag[0] + "\t" + "No BLAST hit" + "\t" + "hypothetical protein"

f.close()

